package com.javastudy.thread;

public class SuspendResumeTest {

    public static Object baozi = null;

    public static void main(String[] args) throws InterruptedException {
        SuspendResumeTest test = new SuspendResumeTest();
//        test.suspendResumetTest();//正常情况
//        test.suspendResumeDeadLockTest();//死锁情况1
        test.suspendResumeDeadLockTest2();//死锁情况2
    }

    public void suspendResumeTest() throws InterruptedException {
        Thread consumerThread = new Thread(new Runnable() {
            @Override
            public void run() {
                while(baozi == null){
                    System.out.println("1.没有包子，进入等待");
                    Thread.currentThread().suspend();
                }
                System.out.println("2.买到包子了，回家");
            }
        });
        consumerThread.start();
        Thread.sleep(3000);
        System.out.println("生产出一个包子了");
        baozi = new Object();
        System.out.println("通知thread来买包子");
        consumerThread.resume();
    }

    public void suspendResumeDeadLockTest() throws InterruptedException {
        Thread consumerThread = new Thread(() -> {
            while(baozi == null){
                System.out.println("1.没有包子，进入等待");
                synchronized (this){
                    Thread.currentThread().suspend();
                }
            }
            System.out.println("2.买到包子了，回家");
        });
        consumerThread.start();
        Thread.sleep(3000);
        System.out.println("生产出一个包子了");
        baozi = new Object();
        System.out.println("通知thread来买包子");
        synchronized (this){
            consumerThread.resume();
        }
    }

    public void suspendResumeDeadLockTest2() throws InterruptedException {
        Thread consumerThread = new Thread(() -> {
            while(baozi == null){
                System.out.println("1.没有包子，进入等待");
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Thread.currentThread().suspend();
            }
            System.out.println("2.买到包子了，回家");
        });
        consumerThread.start();
        Thread.sleep(3000);
        System.out.println("生产出一个包子了");
        baozi = new Object();
        System.out.println("通知thread来买包子");
        consumerThread.resume();
    }
}
